import logging
from datetime import datetime
from typing import Dict, Any

from flask import Blueprint, jsonify, request as flask_request
from pydantic import BaseModel, ValidationError
import json

from api.service.similar_index_sync_service import sync_data, fetch_data_from_source
from api.service.simliar_index_service import matcher as matcher_service
from api.service.similar_task_service import submit_task, process_pending_tasks, get_task_result, process_result
from configs import web_config

logger = logging.getLogger(__name__)

app = Blueprint('similar', __name__)


# 请求/响应模型
class MatchRequest(BaseModel):
    data: Dict[str, Any]
    meta: Dict[str, Any]


@app.post("/materials/similarity/match")
async def match_handler():
    data = []
    try:
        # 1. 获取 JSON 数据
        json_data = flask_request.get_json()
        if not json_data:
            return jsonify({"error": "No JSON payload provided"}), 400

        # 2. 用 Pydantic 验证并解析
        try:
            request_model = MatchRequest(**json_data)
        except ValidationError as e:
            return jsonify({"error": "Validation error", "details": e.errors()}), 400

        # 3. 使用解析后的数据
        data = request_model.data
        meta = request_model.meta
        if not web_config.SIMILAR_INDEX:
            fetch_data_from_source(None, data.get("tree_id", ""))
        results = matcher_service.find_most_similar(
            current=data,
            top_k=meta.get("top_k", 1),
            min_match_count=meta.get("min_match_field", 1),
            category=data.get("tree_id", "default"),
        )
        res = process_result(results)
        return jsonify({
            "code": "200",
            "message": f"匹配成功",
            "requestId": meta.get('requestId'),
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "data": res,
        }), 200
    except Exception as e:
        logging.error(f"match_handler: {e}")
        return jsonify({
            "code": "201",
            "msgCode": "999",
            "message": f"配置失败"
        }), 200
    finally:
        if not web_config.SIMILAR_INDEX:
            matcher_service.clear(data.get("tree_id", ""))


@app.post("/materials/similarity/submit")
async def submit_handler():
    """提交任务接口"""
    try:
        # 1. 获取 JSON 数据
        json_data = flask_request.get_json()
        if not json_data:
            return jsonify({"error": "No JSON payload provided"}), 400

        # 2. 用 Pydantic 验证并解析
        try:
            request_model = MatchRequest(**json_data)
        except ValidationError as e:
            return jsonify({"error": "Validation error", "details": e.errors()}), 400

        # 3. 使用解析后的数据
        data = request_model.data
        meta = request_model.meta
        obj = {"data": data,
               "meta": {"top_k": meta.get("top_k", 1),
                        "min_match_count": meta.get("min_match_field", 1),
                        "category": data.get("tree_id", "default"),
                        "requestId": meta.get("requestId", ""),
                        "timestamp": meta.get("timestamp", ""),
                        "sourceSystem": meta.get("sourceSystem", ""),
                        "operator": meta.get("operator", ""),
                        },
               }
        request_body = json.dumps(obj, ensure_ascii=False, indent=2)
        results = submit_task(request_body)
        return jsonify({
            "code": "200",
            "message": f"请求已接收，任务创建成功",
            "msg_en": "request is accepted,task is created",
            "requestId": meta.get("requestId", ""),
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "data": results,
        }), 200
    except Exception as e:
        logging.error(f"submit_handler: {e}")
        return jsonify({
            "code": "201",
            "msgCode": "999",
            "message": f"失败:{e}"
        }), 200


@app.get("/materials/similarity/timer")
async def timer_handler():
    """定时调度接口"""
    try:
        process_pending_tasks()
        return jsonify({
            "code": "200",
            "message": f"调度成功"
        }), 200
    except Exception as e:
        logging.error(f"timer_handler: {e}")
        return jsonify({
            "code": "201",
            "msgCode": "999",
            "message": f"失败:{e}"
        }), 200


@app.get("/materials/similarity/index")
async def index_handler():
    """定时调度接口"""
    try:
        sync_data()
        return jsonify({
            "code": "200",
            "message": f"调度成功"
        }), 200
    except Exception as e:
        logging.error(f"timer_handler: {e}")
        return jsonify({
            "code": "201",
            "msgCode": "999",
            "message": f"失败:{e}"
        }), 200


@app.post("/materials/similarity/sync_task")
async def match_task():
    """获取任务接口"""
    try:
        # 1. 获取 JSON 数据
        json_data = flask_request.get_json()
        if not json_data:
            return jsonify({"error": "No JSON payload provided"}), 400

        # 2. 用 Pydantic 验证并解析
        try:
            request_model = MatchRequest(**json_data)
        except ValidationError as e:
            return jsonify({"error": "Validation error", "details": e.errors()}), 400

        meta = request_model.meta
        results = get_task_result(meta.get("task_id", ""))
        return jsonify({
            "code": "200",
            "message": f"成功",
            "msg_en": "request is accepted,task is created",
            "msgCode": "",
            "requestId": meta.get("requestId", ""),
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "data": json.loads(results),
        }), 200
    except Exception as e:
        logging.error(f"match_task: {e}")
        return jsonify({
            "code": "201",
            "msgCode": "999",
            "message": f"失败:{e}"
        }), 200
